var util = require('../../../utils/util.js')
var app = getApp()
var template = require('../tabbar/template.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    statusType: ["用户待付款","待发货","已送到货","全部"],
    hasRefund: false,
    currentType: 0,
    tabClass: ["",  ""],
    isEnd:false,
    logisticsStatusItems: [
			'客户未收到货',
			'客户已收到货'
    ],
    typeItems: [
			'我要退款(无需退货)',
			'我要退货退款',
			'我要换货',
    ],
    reasons: [
			"不喜欢/不想要",
			"空包裹",
			"未按约定时间发货",
			"快递/物流一直未送达",
			"货物破损已拒签",
			"退运费",
			"规格尺寸与商品页面描述不符",
			"功能/效果不符",
			"质量问题",
			"少件/漏发",
			"包装/商品破损",
			"发票问题",
		],
    stv: {
      windowWidth: 0,
      lineWidth: 0,
      offset: 0,
      tStart: false
    },
    activeTab: 0,
    loadingStatus: false,
    loadingMore:false,
    isShow:false
  },

  //离开页面时再返回
  onUnload: function (e) {
    
    
  },
 
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      //切换选中
      currentType: parseInt(options.type)
    });
  
    try {
      let { tabs } = this.data;
      var res = wx.getSystemInfoSync()
      this.windowWidth = res.windowWidth;
      this.data.stv.lineWidth = this.windowWidth / this.data.tabs.length;
      this.data.stv.windowWidth = res.windowWidth;
      this.setData({ stv: this.data.stv })
      this.tabsCount = tabs.length;
    } catch (e) {
    }
    wx.setNavigationBarTitle({
      title: '订单列表',
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  //切换订单状态
  statusTap: function (e) {
    const curType = e.currentTarget.dataset.index;
    this.data.currentType = curType
    this.setData({
      currentType: curType
    });
    this.onShow();
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow(){
    let  that = this;
    wx.hideHomeButton()
      // 获取订单列表
      that.setData({
        loadingMore: true,
        isShow:true
      })
     
      
       this.getOrderList()
  },
  getOrderList: function () {
    var that = this;
     
    var where ={}
    if(that.data.currentType==0){
      where = {status:0}
    
    }else if(that.data.currentType==1){
      //用户付款成功，待发货
      
      where = {status:1,delivered:0}
    }else if(that.data.currentType==2){
      //已经送货到用户手里
      where = {status:2}
    }else{
      where={}
    }
    
    wx.cloud.callFunction({
      // 云函数名称
      name: 'crud',
      // 传给云函数的参数
      data: {
        db:"orders",
        type:"getall",
        data:"",
        indexKey:"",
        //待筛选的参数-xx >0
        //commandtype:[],
        condition:where,
      },
    })
    .then(res => {
      if(res.result){
        if(res.result.data.length > 0){
          
          that.setData({
            orderList:res.result.data,
            isEnd:true,
            loadingMore: false,
            isShow:false
          })
          return
        }else{
          that.setData({
            orderList: null,
            isEnd:true,
            loadingMore: false,
            isShow:false
          }); 
        }
        return
      }else{
        that.setData({
          orderList: null,
          isEnd:true,
          loadingMore: false,
          isShow:false
        }); 
      }
    })
    .catch(console.error)
   
  },
  orderDetail: function (e) {
    var orderId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: "/pages/order-details/index?id=" + orderId
    })
  },
  //去配送
  toPeisong(e){
    const that = this;
    const orderId = e.currentTarget.dataset.id;
  
    wx.showModal({
      title: '确定要配送这个订单吗？',
      content: '',
      success: function (res) {
        if (res.confirm) {
          const db = wx.cloud.database()
          db.collection('orders').where({
            _id:  orderId
          }).get({
            success: res => {
              if( res.data[0].delivered == 1){
                wx.showModal({
                  title: '该订单已被领取',
                  content: '该订单已被领取！',
                  showCancel: false,
                })
                that.onShow();
              }else{
                db.collection('orders').doc(orderId).update({
                  data: {
                    delivered: 1,
                    deliveredMan:wx.getStorageSync('openid')
                  },
                  success: function(res) {
                  
                    that.getOrderList();
      
                  }
                })
              }
            
            }
          })
         
         
          that.getOrderList();
        }
      }
    })
  },

  swiperchange: function (e) {
    //console.log('swiperCurrent',e.detail.current)
    let { tabs, stv, activeTab } = this.data;
    activeTab = e.detail.current;
    this.setData({ activeTab: activeTab })
    stv.offset = stv.windowWidth * activeTab;
    this.setData({ stv: this.data.stv })
  },
  handlerEnd(e) {
   
    let { clientX, clientY } = e.changedTouches[0];
    let endTime = e.timeStamp;
    let { tabs, stv, activeTab } = this.data;
 
    let { offset, windowWidth } = stv;
    //快速滑动
    if (endTime - this.tapStartTime <= 300) {
      console.log('快速滑动')
      //判断是否左右滑动(竖直方向滑动小于50)
      if (Math.abs(this.tapStartY - clientY) < 50) {
        //Y距离小于50 所以用户是左右滑动
        console.log('竖直滑动距离小于50')
        if (this.tapStartX - clientX > 5) {
          //向左滑动超过5个单位，activeTab增加
          console.log('向左滑动')
          if (activeTab < this.tabsCount - 1) {
            this.setData({ activeTab: ++activeTab })
          }
        } else if (clientX - this.tapStartX > 5) {
          //向右滑动超过5个单位，activeTab减少
          console.log('向右滑动')
          if (activeTab > 0) {
            this.setData({ activeTab: --activeTab })
          }
        }
        stv.offset = stv.windowWidth * activeTab;
      } else {
        //Y距离大于50 所以用户是上下滑动
        console.log('竖直滑动距离大于50')
        let page = Math.round(offset / windowWidth);
        if (activeTab != page) {
          this.setData({ activeTab: page })
        }
        stv.offset = stv.windowWidth * page;
      }
    } else {
      let page = Math.round(offset / windowWidth);
      if (activeTab != page) {
        this.setData({ activeTab: page })
      }
      stv.offset = stv.windowWidth * page;
    }
    stv.tStart = false;
    this.setData({ stv: this.data.stv })
  },
  handlerStart(e) {
    console.log('handlerStart')
    let { clientX, clientY } = e.touches[0];
    this.startX = clientX;
    this.tapStartX = clientX;
    this.tapStartY = clientY;
    this.data.stv.tStart = true;
    this.tapStartTime = e.timeStamp;
    this.setData({ stv: this.data.stv })
  },
  handlerMove(e) {
    console.log('handlerMove')
    let { clientX, clientY } = e.touches[0];
    let { stv } = this.data;
    let offsetX = this.startX - clientX;
    this.startX = clientX;
    stv.offset += offsetX;
    if (stv.offset <= 0) {
      stv.offset = 0;
    } else if (stv.offset >= stv.windowWidth * (this.tabsCount - 1)) {
      stv.offset = stv.windowWidth * (this.tabsCount - 1);
    }
    this.setData({ stv: stv });
  },
 
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
   
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
     
   let that = this;
   that.getOrderList()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})